using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;

namespace Lzfy_His_Service.Services
{
    /// <summary>
    /// 坐席账号清理定时任务服务
    /// </summary>
    public class AgentAccountCleanupService : BackgroundService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<AgentAccountCleanupService> _logger;
        private readonly IConfiguration _configuration;
        private readonly TimeSpan _cleanupInterval;

        public AgentAccountCleanupService(
            IServiceProvider serviceProvider,
            ILogger<AgentAccountCleanupService> logger,
            IConfiguration configuration)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
            _configuration = configuration;
            
            // 从配置中读取清理间隔，默认60分钟
            var intervalMinutes = _configuration.GetValue<int>("AgentAccount:CleanupIntervalMinutes", 60);
            _cleanupInterval = TimeSpan.FromMinutes(intervalMinutes);
            
            _logger.LogInformation("坐席账号清理服务已启动，清理间隔: {Interval} 分钟", intervalMinutes);
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("坐席账号清理定时任务开始执行");
            
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    await PerformCleanupAsync();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "执行坐席账号清理任务时发生错误");
                }
                
                try
                {
                    await Task.Delay(_cleanupInterval, stoppingToken);
                }
                catch (OperationCanceledException)
                {
                    // 服务正在停止，这是正常的
                    break;
                }
            }
            
            _logger.LogInformation("坐席账号清理定时任务已停止");
        }

        private async Task PerformCleanupAsync()
        {
            try
            {
                using var scope = _serviceProvider.CreateScope();
                var agentAccountService = scope.ServiceProvider.GetRequiredService<IAgentAccountService>();
                
                var cleanedCount = await agentAccountService.CleanupExpiredAccountsAsync();
                
                if (cleanedCount > 0)
                {
                    _logger.LogInformation("定时清理任务完成，清理了 {Count} 个过期的坐席账号权限", cleanedCount);
                }
                else
                {
                    _logger.LogDebug("定时清理任务完成，没有需要清理的过期坐席账号");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行坐席账号清理操作时发生错误");
            }
        }

        public override async Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("坐席账号清理服务正在停止...");
            await base.StopAsync(stoppingToken);
            _logger.LogInformation("坐席账号清理服务已停止");
        }
    }
}